<%--

  User: PING
  Date: 2022/9/7
  Time: 9:50
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"
        import="com.javaweb.common.DBUtil"
        import="com.javaweb.common.StringTool"
        import="com.javaweb.common.DispatcherTool"%>
<%@ page import="com.javaweb.entity.User" %>
<%@ page import="java.util.concurrent.ConcurrentHashMap" %>
<%@ page import="com.javaweb.entity.Teacher" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.javaweb.entity.Comment" %>

<html>
<meta charset="UTF-8">
<head>
    <title></title>
</head>
<body>
    <%
        // process the request from login UI
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name") ;
        String pwd = request.getParameter("pwd") ;

        if (StringTool.isEmpty(name) || StringTool.isEmpty(pwd)) {
            DispatcherTool.responseWithInfo(response, "login.jsp", "名字或密码为空！");
            return ;
        }
        User user = DBUtil.userLogin(name, pwd) ;
        if (user == null) {
            DispatcherTool.responseWithInfo(response, "login.jsp", "密码不正确！");
            return ;
        }
     /*   request.getRequestDispatcher("show.jsp?user=" + StringTool.URLEncodeInUTF(name))
                          .forward(request, response);*/
        /**
         * loading data
         */
        Map<Integer, Integer> voteMap = new ConcurrentHashMap<>() ;
        Map<Integer, Integer> favMap = new ConcurrentHashMap<>() ;
        Map<Integer, Integer> unfavMap = new ConcurrentHashMap<>() ;
        Map<Integer, List<Comment>> comMap = new ConcurrentHashMap<>() ;
        List<Teacher> teacherList = DBUtil.queryAllTeacher() ;
        /**
         * for validated user, cache user information in the sesson.
         */
        session.setAttribute("user", user) ;
        /**
         * caching teacher data
         */
        session.setAttribute("teacherList", teacherList) ;
        if (teacherList.size() > 0) {
            teacherList.forEach(teacher -> {
                favMap.put(teacher.getId(), teacher.getFavNum()) ;
                unfavMap.put(teacher.getId(), teacher.getUnfavNum()) ;
                voteMap.put(teacher.getId(), teacher.getVote()) ;
                List<Comment> comments = DBUtil.getCommentsForTeacher(teacher.getId()) ;
                if (comments != null) comMap.put(teacher.getId(), comments) ;
             }) ;

        }
        /**
         * Caching statistics into application context.
         */
        application.setAttribute("favMap", favMap) ;
        application.setAttribute("unfavMap", unfavMap) ;
        application.setAttribute("voteMap", voteMap);
        application.setAttribute("comMap", comMap) ;
        response.sendRedirect("show.jsp");



    %>

</body>
</html>
